//
//  LoginViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2020/1/2.
//  Copyright © 2020 辽宁当代. All rights reserved.
//

import UIKit
import SVProgressHUD
import Hero

// MARK: - 登陆
class LoginViewController: UIViewController {

    // MARK: - 属性
    @IBOutlet weak var userName: UITextField!   // 用户名
    @IBOutlet weak var passWord: UITextField!   // 密码
    @IBOutlet weak var tj: UIButton!               // 提交
    @IBOutlet weak var cz: UIButton!               // 重置
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setipNavigationBar()

    }

}


// MARK: - 设置UI界面相关
extension LoginViewController {
    
    private func setipNavigationBar() {
        // 1.设置左侧item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick))
        
        // 2.设置标题
        title = "登陆页面"
        
        // 3.绑定页面按钮
        tj.addTarget(self, action: #selector(tjBtnClick), for: .touchUpInside)  // 提交
        cz.addTarget(self, action: #selector(czBtnClick), for: .touchUpInside)  // 重置
        
    }
    
}

// MARK: - 事件监听函数
extension LoginViewController {
    
    // 关闭
    @objc private func closeItemClick() {
        dismiss(animated: true, completion: nil)
    }
    
    // 绑定登陆按钮
    @objc private func tjBtnClick()
    {
        login()
    }
    
    // 绑定重置按钮
    @objc private func czBtnClick()
    {
        self.userName.text = ""
        self.passWord.text = ""
        print("重置成功!")
    }
}



// MARK: - 请求接口
extension LoginViewController {
    
    private func login() {
        Thread.sleep(forTimeInterval: 0.4)
        // 获取绑定的标签
        let txtUser = userName.text
        let txtPsd = passWord.text
        if txtUser == "" {
            //SVProgressHUD.showError(withStatus: "请填写用户名")
            if #available(iOS 13.0, *) {
                self.showMsgbox(_message: "请填写用户名")
            }
            print("请填写用户名")
            return
        }
        
        if txtPsd == "" {
            //SVProgressHUD.showError(withStatus: "请填写密码")
            if #available(iOS 13.0, *) {
                self.showMsgbox(_message: "请填写密码")
            }
            print("请填写密码")
            return
        }
        
        let str = [txtUser, txtPsd, "","","phone","",""]
        
        NetworkTools.share.user_login(code: str as Array<Any>) { (result, error) in
            
            // 错误校验
            if error != nil
            {
                print(error!)
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("数据获取失败")
                return
            }
            
            // 解包
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    //let code : Int = Int(arr["RETCODE"] as! String)!
                    //if(Int(truncating: NSNumber(value: code)) < 0 ) {
                    print(arr)
                    if Int(self._retcode(res: result!))! < 0 {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "登陆失败")
                        }
                        print(resultArray)
                    } else {
                        //self.saveWithFile(arr: arr)
                        let user = User(dict: arr)
                        user.U = arr["U"] as? String
                        user.RETCODE = arr["RETCODE"] as? String
                        
                        // 获取沙盒路径
                        var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
                        userPath = (userPath as NSString).appendingPathComponent("data.plist")
                        // 保存对象
                        NSKeyedArchiver.archiveRootObject(user, toFile: userPath)
                        
                        if #available(iOS 13.0, *) {
                            self.showMsgboxOK(_message: "登陆成功", url: "Index")
                        }
                        /*self.dismiss(animated: false) {
                            UIApplication.shared.keyWindow?.rootViewController =  BaseViewController()
                        }*/
                    }
                    
                }
            }
            
        }
        
    }
    
    // 获取retcode
    func _retcode(res : [String : AnyObject]) -> String {
        var result : [String : AnyObject] = [:]
        if let _rep = res["REP"] as? [String : AnyObject] {
            result = (_rep["RESULT"] as? [String : AnyObject])!
        }
        return result["RETCODE"] as! String
    }
    
    // 登陆专用归档
    func saveWithFile(arr : [String : AnyObject])
    {
        // 1、获得沙盒的根路径
        let home = NSHomeDirectory() as NSString
        // 2、获得Documents路径，使用NSString对象的stringByAppendingPathComponent()方法拼接路径
        let docPath = home.appendingPathComponent("Documents") as NSString
        // 3、获取文本文件路径
        let filePath = docPath.appendingPathComponent("data.plist")
        let dataSource = NSMutableArray()
         dataSource.add(arr["RETCODE"]!) // retcode
         dataSource.add(arr["U"]!)  // u
        //print(dataSource)
        // 4、将数据写入文件中
        dataSource.write(toFile: filePath, atomically: true)
        //print(filePath)
    }
    
    
    
}



// MARK: - 自定义函数
@available(iOS 13.0, *)
extension LoginViewController {
    //MARK: - ALert跳转
    @objc func showMsgbox(_message: String, _title: String = "提示") {
        
        let alert = UIAlertController(title: _title, message: _message, preferredStyle: UIAlertController.Style.alert)
        let btnOK = UIAlertAction(title: "好的", style: .default, handler: nil)
        alert.addAction(btnOK)
        self.present(alert, animated: true, completion: nil)
    }
    
    //MARK: - ALert跳转 成功
    @objc func showMsgboxOK(_message: String, _title: String = "提示" , url : String) {
        let alert = UIAlertController(title: _title, message: _message, preferredStyle: UIAlertController.Style.alert)
        let btnOK = UIAlertAction(title:"好的", style: .default) { (cancelAction)in
            print("ok")
            // 成功跳转
            self.goBack(identifier: url)
        }
           alert.addAction(btnOK)
           self.present(alert, animated: true, completion: nil)
       }
    
    /// 跳转
    @objc func goBack(identifier: String)
    {
        let login = UIStoryboard.init(name: "Main", bundle: nil)
        let play = login.instantiateViewController(identifier: identifier)
                 
        // self.navigationController?.pushViewController(play, animated: true)
        // 全屏跳转
        play.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        
        // 左右横跳
        play.hero.isEnabled = true
        play.hero.modalAnimationType = .selectBy(presenting: .pull(direction: .left), dismissing: .uncover(direction: .right))
        self.present(play, animated: false, completion: nil)
    }
    
}
